package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.OrderTo;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.LoginRespVo;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.FeignCartService;
import com.atguigu.gulimall.order.feign.FeignMemberService;
import com.atguigu.gulimall.order.feign.FeignProductService;
import com.atguigu.gulimall.order.feign.FeignWareService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    FeignCartService feignCartService;

    @Autowired
    FeignMemberService feignMemberService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    FeignWareService feignWareService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    FeignProductService feignProductService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 订单确认页返回需要的数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        LoginRespVo loginUser = LoginUserInterceptor.loginUserThreadLoadl.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //收货地址
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = feignMemberService.getAddress(loginUser.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //选中的购物项
            //feign在远程调用之前会调用拦截器 RequestInterceptor
            //为了解决丢失header query 信息  必须加拦截器
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> orderItemVos = feignCartService.currentUserCartItems();
            confirmVo.setItems(orderItemVos);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = feignWareService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> skuHasStockVos = r.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if (skuHasStockVos != null) {
                Map<Long, Boolean> mapHasStock = skuHasStockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(mapHasStock);
            }
        });

        CompletableFuture.allOf(addressFuture, cartFuture).get();

        //用户积分
        Integer integration = loginUser.getIntegration();
        confirmVo.setIntegration(integration);

        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId(), token, 30, TimeUnit.MINUTES);
        return confirmVo;
    }


    //@GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderRespVo submitOrder(OrderSubmitVo vo) {
        LoginRespVo loginUser = LoginUserInterceptor.loginUserThreadLoadl.get();
        orderSubmitVoThreadLocal.set(vo);
        SubmitOrderRespVo respVo = new SubmitOrderRespVo();
        respVo.setCode(0);
        //创建订单：验令牌、验价格...
        //1、验证令牌[令牌的对比和删除必须保证原子性]
        //以下脚本：如果不存在返回0，删除成功则返回1
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId()),
                orderToken
        );
        if (result == 0) {
            //令牌验证失败
            respVo.setCode(1);
            return respVo;
        } else {
            //验证成功,下单
            OrderCreateTo order = createOrder();
            //验价
            BigDecimal payPrice = vo.getPayPrice();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比
                //保存订单
                saveOrder(order);
                //库存锁定,只要有异常就撤回之前的订单数据
                //订单号，所有订单项信息（skuId,num,skuName）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    itemVo.setPrice(item.getSkuPrice());
                    itemVo.setCount(item.getSkuQuantity());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);

                //为了保证高并发、库存服务自己回滚，可以发消息给库存服务
                //库存服务本身也可以使用自动解锁模式  使用消息队列完成
                R r = feignWareService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁成功了
                    respVo.setOrder(order.getOrder());
                    //TODO 订单创建成功，发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    //int i = 10 / 0;//订单回滚，库存不回滚
                    return respVo;
                } else {
                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                respVo.setCode(2);
            }
        }
        return respVo;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity entity = this.getOne(new QueryWrapper<OrderEntity>()
                .lambda().eq(OrderEntity::getOrderSn, orderSn));
        return entity;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //关闭订单之前，先查询当前订单的状态
        OrderEntity orderDb = this.getById(entity.getId());
        if(orderDb.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            //待付款状态才能关单
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateEntity);
            //发给MQ一个
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity,orderTo);
            try {
                //一定要保证消息100%发出去
                //每一个消息都做好日志记录(给数据库保存每个消息的详细信息)
                //定期扫描数据库，，将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            }catch (Exception e){
                //将没发送成功的消息进行重试发送
                //做
            }
        }
    }


    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
//        for (OrderItemEntity orderItem : orderItems) {
//            orderItemService.save(orderItem);
//        }

    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        createTo.setOrder(orderEntity);
        //2、获取所有的订单项
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);
        createTo.setOrderItems(orderItems);
        //3、计算价格相关
        computerPrice(orderEntity, orderItems);
        return createTo;
    }

    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        //订单价格相关
        BigDecimal total = new BigDecimal("0.00");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        Integer allGrowth = new Integer(0);
        Integer allIntegration = new Integer(0);
        for (OrderItemEntity orderItem : orderItems) {
            total = total.add(orderItem.getRealAmount());
            coupon = coupon.add(orderItem.getCouponAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            allGrowth = allGrowth + orderItem.getGiftGrowth();
            allIntegration = allIntegration + orderItem.getGiftIntegration();
        }
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setGrowth(allGrowth);
        orderEntity.setIntegration(allIntegration);

    }

    private OrderEntity buildOrder(String orderSn) {
        LoginRespVo loginUser = LoginUserInterceptor.loginUserThreadLoadl.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(loginUser.getId());
        //获取收获地址信息
        OrderSubmitVo submitVo = orderSubmitVoThreadLocal.get();
        //远程获取运费信息
        R fare = feignWareService.getFare(submitVo.getAddrId());
        FareRespVo fareResp = fare.getData(new TypeReference<FareRespVo>() {
        });
        //设置运费信息
        orderEntity.setFreightAmount(fareResp.getFarePrice());
        //设置收货人信息
        orderEntity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareResp.getAddress().getName());
        orderEntity.setReceiverPhone(fareResp.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareResp.getAddress().getProvince());
        orderEntity.setReceiverCity(fareResp.getAddress().getCity());
        orderEntity.setReceiverRegion(fareResp.getAddress().getRegion());

        //订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setDeleteStatus(0);

        return orderEntity;
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = feignCartService.currentUserCartItems();
        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            orderItemEntityList = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntityList;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息，订单号
        //2、商品的SPU信息
        Long skuId = cartItem.getSkuId();
        R rSpuInfo = feignProductService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfo = rSpuInfo.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfo.getId());
        orderItemEntity.setSpuBrand(spuInfo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfo.getSpuName());
        orderItemEntity.setCategoryId(spuInfo.getCatalogId());
        //3、商品的SKU信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息
        //5、积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        //6 订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        BigDecimal orignPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        BigDecimal realPrice = orignPrice.subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realPrice);

        return orderItemEntity;
    }

}